package util;

import java.util.List;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class CompareText {
	public static Map<String, Integer[]> wordMap = new HashMap<String, Integer[]>(); // 保存每个词在各个文本出现的次数

	public static double getProduct(Integer[] a, Integer[] b) {
		int sum = 0;
		if (a.length == b.length) {
			for (int i = 0; i < a.length; i++) {
				sum += a[i]*b[i];
			}
		}
		return sum;
	}
	
	public static  double getProductMod(Integer[] a, Integer[] b){
		double sum1=0;
		double sum2=0;
		for (int i = 0; i < a.length; i++) {
			sum1+=a[i]*a[i];
		}
		for (int i = 0; i < b.length; i++) {
			sum2+=b[i]*b[i];
		}
		return Math.sqrt(sum1)*Math.sqrt(sum2);
	}
	
	//计算两个想来那个的余弦相似度
	public static double getCos(Integer[] a, Integer[] b){
		return getProduct(a, b)/getProductMod(a, b);
	}
	
	public static void main(String[] args) {

		// 初始化wordMap
		for (String word : Reader.readfile()) {
			wordMap.put(word, new Integer[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
		}

		// 获取各个文本所对应的词
		Map<Integer, List<String>> texts = Reader.texts;

		// 比较，计算出每个词在各个文本中出现的次数
		for (Map.Entry<Integer, List<String>> textsEntry : texts.entrySet()) {
			List<String> tempList = textsEntry.getValue();
			for (String textWord : tempList) {
				for (Map.Entry<String, Integer[]> wordMapEntry : wordMap.entrySet()) {
					Integer[] num = wordMapEntry.getValue();
					if (wordMapEntry.getKey().equals(textWord)) {
						num[textsEntry.getKey() - 1]++;
					}
				}
			}
		}

		// 求文档向量
		Map<Integer, Integer[]> vector = new HashMap<Integer, Integer[]>();
		for (int i = 1; i <= 10; i++) {
			vector.put(i, new Integer[wordMap.size()]);
		}
		int j = 0;
		for (Map.Entry<String, Integer[]> wordMapEntry : wordMap.entrySet()) {
			Integer[] count = wordMapEntry.getValue();
			for (int i = 0; i < count.length; i++) {
				Integer[] count2 = vector.get(i + 1);
				count2[j] = count[i];
			}
			j++;
		}
		
		
		//计算十个文档向量的余弦相似度
		double[][] answer = new double[10][10];
		DecimalFormat df=new DecimalFormat("#.#####");
		
		for (int i = 0; i < 10; i++) {
			Integer[] temp=vector.get(i+1);
			for(int k = 0; k<10; k++){
				Integer[] temp2=vector.get(k+1);
				answer[i][k]=Double.parseDouble(df.format(getCos(temp, temp2)));
			}
		}
		for (double[] ds : answer) {
			for (double d : ds) {
				System.out.print(d+"\t");
			}
			System.out.println();
		}
	}
}
